from flask import Flask, request, jsonify
from utils import deepseek_call
import time
from celery import Celery
from settings import CELERY_BROKER_URL, CELERY_RESULT_BACKEND

app = Flask(__name__)

# 异步任务配置（使用Celery+Redis）
app.config["CELERY_BROKER_URL"] = CELERY_BROKER_URL
app.config["CELERY_RESULT_BACKEND"] = CELERY_RESULT_BACKEND
celery = Celery(app.name, broker=app.config["CELERY_BROKER_URL"])
celery.conf.update(app.config)

# 基础功能列表
SUPPORTED_FUNCTIONS = [
    {"name": "translate_zh_to_en", "desc": "中译英"},
    {"name": "translate_en_to_zh", "desc": "英译中"},
    {"name": "summarize", "desc": "文本总结"}
]

# 获取所有功能列表接口
@app.route("/api/functions", methods=["GET"])
def get_functions():
    return jsonify({"code": 200, "data": SUPPORTED_FUNCTIONS})

# 同步调用具体功能接口
@app.route("/api/function/<func_type>", methods=["POST"])
def call_function(func_type):
    data = request.json
    if not data or "text" not in data:
        return jsonify({"code": 400, "msg": "缺少text参数"})
    
    try:
        result = deepseek_call(data["text"], func_type)
        return jsonify({"code": 200, "data": {"result": result}})
    except ValueError as e:
        return jsonify({"code": 404, "msg": str(e)})
    except Exception as e:
        return jsonify({"code": 500, "msg": f"模型调用失败：{str(e)}"})

# 异步任务接口（Celery实现）
@celery.task
def async_deepseek_task(text: str, func_type: str) -> str:
    """Celery异步任务函数"""
    return deepseek_call(text, func_type)

@app.route("/api/async/function/<func_type>", methods=["POST"])
def async_call_function(func_type):
    data = request.json
    if not data or "text" not in data:
        return jsonify({"code": 400, "msg": "缺少text参数"})
    
    # 提交Celery任务
    task = async_deepseek_task.delay(data["text"], func_type)
    return jsonify({
        "code": 200,
        "data": {"task_id": task.id}
    })

@app.route("/api/task/<task_id>", methods=["GET"])
def get_task_status(task_id):
    task = async_deepseek_task.AsyncResult(task_id)
    if task.ready():
        return jsonify({
            "code": 200,
            "data": {"status": "success", "result": task.result}
        })
    else:
        return jsonify({
            "code": 200,
            "data": {"status": "processing"}
        })

# 流式返回接口（SSE实现）
@app.route("/api/stream/function/<func_type>", methods=["POST"])
def stream_call_function(func_type):
    data = request.json
    if not data or "text" not in data:
        return jsonify({"code": 400, "msg": "缺少text参数"})

    def generate():
        # 调用时启用流式
        stream_result = deepseek_call(data["text"], func_type, stream=True)
        for chunk in stream_result:
            time.sleep(0.1)  # 模拟更真实的流式延迟
            yield f"data: {chunk}\n\n"  # SSE格式

    return app.response_class(generate(), mimetype="text/event-stream")

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5001, debug=True)